﻿using System;
using System.Linq;
using System.Threading.Tasks;
using HengTong.Model.Db.Hr;
using Microsoft.EntityFrameworkCore;
using WalkingTec.Mvvm.Core;

namespace HengTong.ViewModel.Person.SysPersonVms;

public partial class SysPersonVm : BaseCRUDVM<SysPerson>
{
    public override async Task DoDeleteAsync()
    {
        var transaction = await DC.Database.BeginTransactionAsync();
        try
        {
            // 先删除学历附件表
            var existingEducationIds = await DC.Set<SysPersonEducation>()
                .Where(e => e.PersonId == Entity.ID)
                .Select(e => e.ID)
                .ToListAsync();

            if (existingEducationIds.Any())
            {
                await DC.Set<SysPersonEducationFile>()
                    .Where(f => existingEducationIds.Contains((Guid)f.PersonEducationId))
                    .ExecuteDeleteAsync();
            }
            // 删除合同附件表
            var existingContractIds = await DC.Set<SysPersonContract>()
                .Where(e => e.PersonId == Entity.ID)
                .Select(c => c.ID)
                .ToListAsync();
            if (existingContractIds.Any())
            {
                await DC.Set<SysPersonContractFile>()
                    .Where(f => existingContractIds.Contains((Guid)f.PersonContractId))
                    .ExecuteDeleteAsync();
            }
            
            // 删除子表
            await DC.Set<SysPersonEducation>().Where(e => e.PersonId == Entity.ID).ExecuteDeleteAsync();// 删除个人教育经历
            await DC.Set<SysPersonFamily>().Where(e => e.PersonId == Entity.ID).ExecuteDeleteAsync();// 删除个人家庭成员
            await DC.Set<SysPersonWork>().Where(e => e.PersonId == Entity.ID).ExecuteDeleteAsync();// 删除个人工作经历
            await DC.Set<SysPersonTrainExam>().Where(e => e.PersonId == Entity.ID).ExecuteDeleteAsync();// 删除个人培训考试
            await DC.Set<SysPersonMedical>().Where(e => e.PersonId == Entity.ID).ExecuteDeleteAsync();// 删除个人体检
            await DC.Set<SysPersonResume>().Where(e => e.PersonId == Entity.ID).ExecuteDeleteAsync();// 删除个人履历
            await DC.Set<SysPersonContract>().Where(e => e.PersonId == Entity.ID).ExecuteDeleteAsync();// 删除个人合同
            // 删除主表
            await base.DoDeleteAsync();

            // 第二种方式：先查再删，或查询后做其他处理，注意要 SaveChangesAsync
            /*
            var family = await DC.Set<SysPersonFamily>()
                .Where(e => e.PersonId == Entity.ID).ToArrayAsync();
            DC.Set<SysPersonFamily>().RemoveRange(family);
            await DC.SaveChangesAsync();
            */

            await transaction.CommitAsync();
        }
        catch (Exception e)
        {
            await transaction.RollbackAsync();
            MSD.AddModelError(" ", $"信息删除异常{e.Message}");
        }
        finally
        {
            await transaction.DisposeAsync();
        }
    }
    
}